IF OBJECT_ID('ssf.job_get_last_run_request_datetime') IS NOT NULL
	DROP FUNCTION ssf.job_get_last_run_request_datetime
GO

CREATE FUNCTION ssf.job_get_last_run_request_datetime (
	@job_id UNIQUEIDENTIFIER
	, @before_run_datetime DATETIME = NULL
)
RETURNS DATETIME
AS
BEGIN
/*
<object_header>

<object_summary>
	<purpose><![CDATA[
In sysjobactivity, a record is maintained per, per SQL Agent session.
For the given job_id, return the maximum run requested date where the job
was requested to start at or before the given date/time, or if NULL, the maximum overall.
Will be NULL if the job has never been requested to run.
	]]></purpose>
</object_summary>

</object_header>
*/

	RETURN (
		SELECT MAX(run_requested_date)
		FROM msdb.dbo.sysjobactivity WITH (NOLOCK)
		WHERE job_id = @job_id
		AND run_requested_date <= ISNULL(@before_run_datetime, GETDATE())
	)
END
GO
